package com.giggle.nacos.discovery;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.ConditionalOnRibbonNacos;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ServerList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.ribbon.PropertiesFactory;
import org.springframework.cloud.netflix.ribbon.RibbonClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;

/**
 * @author guozichen
 * @ClassName:
 * @Description: (nacos ribbon 扩展配置)
 * @date 2020/8/26 14:10
 */
@Configuration(
        proxyBeanMethods = false
)
@ConditionalOnRibbonNacos
@RibbonClients(
        defaultConfiguration = {NacosRibbonExtClientConfiguration.class}
)
public class NacosRibbonExtClientConfiguration {

    @Autowired
    private PropertiesFactory propertiesFactory;

    public NacosRibbonExtClientConfiguration() {
    }

    @Bean
    @Lazy
    @Primary
    public ServerList<?> ribbonServerList(IClientConfig config, NacosDiscoveryProperties nacosDiscoveryProperties) {
        if (this.propertiesFactory.isSet(ServerList.class, config.getClientName())) {
            ServerList serverList = (ServerList)this.propertiesFactory.get(ServerList.class, config, config.getClientName());
            return serverList;
        } else {
            NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
            serverList.initWithNiwsConfig(config);
            return serverList;
        }
    }
}
